﻿using System;
using Nb.Common;
using Nb.Common.SystemDates;

namespace Nb.Licenses.Libs
{
    /// <summary>
    /// 验证当前机器码
    /// </summary>
    public class MachineCodeHelper
    {
        private DateTime? _lastReadDate = null;
        private int _cacheSeconds = 60;
        private string _cacheResult = null;


        public void ClearCache()
        {
            _lastReadDate = null;
            _cacheResult = null;
        }

        public void ResetCacheSeconds(int cacheSeconds)
        {
            _cacheSeconds = cacheSeconds;
        }

        public string ReadMachineCode(bool useCache = false)
        {
            DateTime now = SystemDateHelper.Now();

            if (!useCache || !_lastReadDate.HasValue)
            {
                _cacheResult = readMachineCode();
                _lastReadDate = SystemDateHelper.Now();
                return _cacheResult;
            }

            //使用缓存，需要检测是否过期
            bool expires = _lastReadDate.Value.AddSeconds(_cacheSeconds) > now;
            if (expires)
            {
                _cacheResult = readMachineCode();
                _lastReadDate = SystemDateHelper.Now();
                return _cacheResult;
            }

            return _cacheResult;
        }
        
        /// <summary>
        /// 读取当前的机器码
        /// </summary>
        /// <returns></returns>
        private string readMachineCode()
        {
            var licenseFactory = LicenseManager.GetFactory();

            var machineInfoService = licenseFactory.GetMachineInfoService();
            var machineInfo = machineInfoService.ReadMachineInfo();

            var machineCodeService = licenseFactory.GetMachineCodeService();
            var machineCode = machineCodeService.MakeMachineCode(machineInfo);

            return machineCode;
        }

        /// <summary>
        /// 校验当前机器码和传入的机器码是否相等
        /// </summary>
        /// <param name="machineCode"></param>
        /// <returns></returns>
        private bool validateMachineCode(string machineCode)
        {
            if (string.IsNullOrWhiteSpace(machineCode))
            {
                return false;
            }

            var currentMachineCode = ReadMachineCode();
            return machineCode.NbEquals(currentMachineCode);
        }
    }
}